import InvocationHandler from "./InvocationHandler";
import Session from "../mysql/Session";

export default class TransactionHandler extends InvocationHandler {

    constructor() {
        super();
    }

    async invoke(proxy, method, methodName, args) {
        const session = await new Session();
        Reflect.set(proxy, 'session', session);

        //通过methodName来判断那些方法需要开启事务
        const ta = proxy['transMethods'];
        let result;

        if (ta && ta.indexOf(methodName) >= 0) {   //开启事务
          
            const transaction = await session.beginTransaction();
            if (!transaction) {      //开启事务成功
                try{
                    console.log("开启事务");
                    result = await super.invoke(proxy, method, methodName, args);
                    console.log("提交事务");
                    await session.commit();
                }catch (e) {
                     await session.rollback();
                     this.handlerError(e);

                }
            }
        }else{
            try{
                result = await super.invoke(proxy, method, methodName, args);
            }catch (e) {
                this.handlerError(e)
            }
        }
        return result;
    }

    /**
     * 处理错误
     * @param e
     */
    handlerError(e) {
        switch (e.errno) {
            case 1062:    //索引重复
                throw ({message: "索引重复,请重新创建!"})
                break;
            case 0:
                break;
            default:
                throw (e);
        }


    }


}
